
"""
It provides the function to convert the endians of 2, 4, 8 octets.

It also supplies an exported interface <code>Trans</code> with the short name \
<b>EDN</b> (<code>EDN.Trans</code>) to enable the conversion from other \
plug-ins."""

__aof__ = ('Endian Translator', 'EDN')
__version__ = "1.11"
__options__ = "choice width 2-Octet,4-Octet,8-Octet"


def _Trans(data, reqs):
    ret = None

    try:
        w = int(str(reqs.get('width', '')).replace('-Octet', ''))
    except (TypeError, ValueError):
        w = 4

    lx = len(data)
    if lx % w == 0:
        ret = ''
        for k in range(0, lx, w):
            va = ''
            for n in range(w):
                va = data[k + n] + va
            ret += va
    else:
        raise Exception("Data length (%d) isn't aligned to "
                        "the purposed length (%d)." % (lx, w))

    return ret


class _Endian:
    __referral__ = (('Trans', _Trans),)

    def Transfer(self, data, *args, **kws):
        reqs = dict()
        if '_i' in kws and hasattr(kws['_i'], 'options'):
            reqs = kws['_i'].options or dict()

        return _Trans(data, reqs)


def orgService():
    return _Endian
